package com.tengju.user.infrastructure.repository.convert;

import com.tengju.user.domain.model.login.UserAccount;
import com.tengju.user.domain.model.login.UserAccountId;
import com.tengju.user.domain.model.login.UserType;
import com.tengju.user.domain.model.user.*;
import com.tengju.user.domain.shared.IdObject;
import com.tengju.user.infrastructure.persistence.mybatis.dataobject.UserAccountDO;
import com.tengju.user.infrastructure.persistence.mybatis.dataobject.UserInfoDO;
import com.tengju.user.infrastructure.shared.InfraException;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.Optional;

/**
 * @author wuziyang
 */
public class UserAccountConvert {

    public static UserAccount convertUserDOToUser(UserAccountDO userAccountDO) {
        if (userAccountDO == null) {
            return null;
        }

        UserType userType = UserType.fromVal(userAccountDO.getUserType());

        UserId userId = null;
        StaffId staffId = null;
        if (userType == UserType.USER) {
            userId = new UserId(userAccountDO.getOutId());
        } else if (userType == UserType.STAFF) {
            staffId = new StaffId(userAccountDO.getOutId());
        }
        return new UserAccount(
                new UserAccountId(userAccountDO.getAccountId()),
                userAccountDO.getUsername(),
                userAccountDO.getPassword(),
                userType,
                userId,
                staffId,
                userAccountDO.getLastLoginIp(),
                userAccountDO.getLastLoginTime() == null ? null : LocalDateTime.ofInstant(userAccountDO.getLastLoginTime().toInstant(), ZoneId.systemDefault()),
                userAccountDO.getVersion()
        );
    }


    public static UserAccountDO convertUserAccountToDO(UserAccount userAccount) {
        UserAccountDO userAccountDO = new UserAccountDO();
        long outId = 0L;
        if (UserType.USER == userAccount.getUserType()) {
            outId = userAccount.getUserId().getValue();
        } else if (UserType.STAFF == userAccount.getUserType()) {
            outId = userAccount.getStaffId().getValue();
        } else {
            throw new InfraException("用户类型错误");
        }
        userAccountDO.setAccountId(Optional.ofNullable(userAccount.getAccountId()).map(IdObject::getValue).orElse(null));
        userAccountDO.setUsername(userAccount.getUsername());
        userAccountDO.setPassword(userAccount.getPassword());
        userAccountDO.setUserType(userAccount.getUserType().getVal());
        userAccountDO.setOutId(outId);
        userAccountDO.setLastLoginIp(userAccount.getLastLoginIp());
        userAccountDO.setLastLoginTime(userAccount.getLastLoginTime() == null ? null : Date.from(userAccount.getLastLoginTime().atZone(ZoneId.systemDefault()).toInstant()));
        userAccountDO.setVersion(userAccount.getVersion());

        return userAccountDO;
    }
}
